package com.ywl.stream;

import com.ywl.entity.Author;
import com.ywl.entity.Book;
import com.ywl.utils.AuthorFactory;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * 终结操作 foreach
 *
 * @author 24040
 * @name StreamDemo04
 * @date 2022-08-22 10:37
 */
public class StreamDemo05 {

    public static void main(String[] args) {
        List<Author> authors = AuthorFactory.getAuthors();
        //test02(authors);
        test03(authors);
    }

    /**
     * 输出所有作家的名字
     */
    private static void test01(List<Author> authors) {
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));
    }

    /**
     * 打印这些作家的所出书籍的数目，注意删除重复元素。
     * @param authors
     */
    private static void test02(List<Author> authors){
        long count = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);
    }

    /**
     * 分别获取这些作家的所出书籍的最高分和最低分并打印。
     */
    private static void test03(List<Author> authors){
        //获取最高分
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .max((o1, o2) -> o1 - o2);
        System.out.println(max.get());

        //获取最低分
        Optional<Integer> min = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .min((o1, o2) -> o1 - o2);
        System.out.println(min.get());
    }

}
